package com.alex.server.controller;

import com.alex.server.pojo.RespBean;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 验证码生成工具
 */
@RestController
public class CaptchaController {
    @Autowired
    public PasswordEncoder passwordEncoder;
    @Autowired
    public DefaultKaptcha defaultKaptcha;
    @ApiOperation(value = "验证码")
    @GetMapping(value = "/captcha",produces = "image/jpg")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        boolean matches = passwordEncoder.matches("123456", "$2a$10$kr7G1WBvgfFf577P.8m0gu9G6p4eWTd4hIv28dU0RmZ7qDhal4WyS");
        System.out.println(matches);
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpg");
        byte[] captcha = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        try {
            //先创建一个文本
            String createText = defaultKaptcha.createText();
            // 将生成的验证码保存在session中
            request.getSession().setAttribute("rightCode", createText);
            System.out.println();
            //根据文本验证码内容创建图形验证码
            BufferedImage bi = defaultKaptcha.createImage(createText);
            //输出流,输出图片
            ImageIO.write(bi, "jpg", out);
        } catch (Exception e) {
            e.printStackTrace();
        }

        captcha = out.toByteArray();

        ServletOutputStream sout = response.getOutputStream();
        sout.write(captcha);
        sout.flush();
        sout.close();
    }
}

